package JAVA并发;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author zhangmin
 * @create 2022-03-15 21:05
 * 九、线程不安全示例
 * 如果多个线程对同一个共享数据进行访问而不采取同步操作的话，那么操作的结果是不一致的。
 * 多线程进行++，最后结果不对
 */
public class ThreadUnsafeExample9 {
    private int cnt=0;

    public void add(){
        cnt++;
    }
    public int get(){
        return  cnt;
    }

    public static void main(String[] args) throws InterruptedException {
        final int threadsize=1000;
        ThreadUnsafeExample9 e=new ThreadUnsafeExample9();
        final CountDownLatch countDownLatch=new CountDownLatch(threadsize);
        ExecutorService executorService= Executors.newCachedThreadPool();
        for (int i = 0; i < threadsize; i++) {
            executorService.execute(()->{
                e.add();
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        System.out.println(e.get());
    }
}
